﻿using Sliver.Roadnet.RawInfo;
using System.Collections.Generic;
using Sliver.Utility;
using UnityEngine;

namespace Sliver.Roadnet.Components
{
    public interface ITrafficLightBehaviour
    {
        void SetStatus(int status);
    }

    public class TrafficLightPoint : MonoBehaviour, ITrafficLightBehaviour
    {
        protected MeshRenderer meshRenderer;

        public Material yellow;
        public Material red;
        public Material green;

        protected void Awake()
        {
            meshRenderer = GetComponent<MeshRenderer>();
        }

        public void SetStatus(int status)
        {
            if (status > 0)
            {
                meshRenderer.sharedMaterial = green;
            }
            else if (status < 0)
            {
                meshRenderer.sharedMaterial = red;
            }
            else
            {
                meshRenderer.sharedMaterial = yellow;
            }
        }
    }

    public class TrafficLightGroup : ITrafficLightBehaviour
    {
        protected List<TrafficLightPoint> Lights = new List<TrafficLightPoint>();

        public TrafficLightGroup(Transform parent, RawRoadLinkInfo info)
        {
            foreach (RawLanelinkInfo laneLink in info.laneLinks)
            {
                TrafficLightPoint point = GameObject.Instantiate(TrafficLightPointPrototype, parent);
                point.transform.position = laneLink.points[0].xz3() + new Vector3(0, 4.4f, 0);
                Lights.Add(point);

                // TrafficLightPoint point2 = GameObject.Instantiate(TrafficLightPointPrototype, parent);
                // point2.transform.position = laneLink.points[laneLink.points.Count - 1].xz3() + new Vector3(0, 4.4f, 0);
                // Lights.Add(point2);
            }
        }

        public void SetStatus(int status)
        {
            foreach (TrafficLightPoint lightPoint in Lights)
            {
                lightPoint.SetStatus(status);
            }
        }

        protected static TrafficLightPoint TrafficLightPointPrototype;

        static TrafficLightGroup()
        {
            TrafficLightPointPrototype = Resources.Load<TrafficLightPoint>("Roadnet/traffic_light_point");
        }
    }
}
